﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FBConnectAuth;
using System.Configuration;
using facebook;
using facebook.web;
using System.Web.Security;

namespace Manazra.Models
{
    public class UserAuth
    {
        private ManazraDataContext dc = new ManazraDataContext();

        public string UserID { get; private set; }
        public string UserName { get; private set; }
        public string FormattedUserName { get; private set; }

        public bool Authenticated { get; private set; }
        public bool IsFacebookUser { get; private set; }
        public bool IsNewFacebookUser { get; private set; }
        public FBConnectSession FBSession { get; private set; }
        
        //performs authentication and sets up necessary params
        public void Authenticate()
        {
            //facebook authentication params
            string apiKey = ConfigurationManager.AppSettings["FBApiKey"];
            string secretKey = ConfigurationManager.AppSettings["FBSecretKey"];
            string fbIdent = ConfigurationManager.AppSettings["FBIdent"];

            //first check for facebox authentication
            FBConnectAuthentication fbAuth = new FBConnectAuthentication(apiKey, secretKey);
            if (fbAuth.Validate() == ValidationState.Valid)
            {
                //lets retrieve the session
                FBSession = fbAuth.GetSession();                

                //if its a new user - lets save their information to our database
                FBAddUser(FBSession);

                //pull up information from our database
                FacebookUser FacebookUser = dc.FacebookUsers.SingleOrDefault(u => u.UserId == FBSession.UserID);

                //update user properties
                UserID = FacebookUser.UserId;
                UserName = FacebookUser.UserId + fbIdent + FacebookUser.UserName;
                FormattedUserName = FacebookUser.UserName;
                IsFacebookUser = true;
                Authenticated = true;
            }
            //otherwise use our regular aspnet membership authentication
            else
            {
                MembershipUser MembershipUser = Membership.GetUser();
                if (MembershipUser != null)
                {
                    //update user properties
                    UserID = MembershipUser.ProviderUserKey.ToString();
                    UserName = MembershipUser.UserName;
                    FormattedUserName = MembershipUser.UserName;
                    Authenticated = true;
                }
            }
        }

        //adds facebook user information to our database
        private void FBAddUser(FBConnectSession fbSession)
        {
            //get user id
            string fbUserId = fbSession.UserID;
            string fbUserName = String.Empty;

            //first check if the user isnt already in database
            if (dc.FacebookUsers.Count(u => u.UserId == fbUserId) == 0)
            {
                //use api to get user name
                API fbApi = LoadFBApi();
                if (fbApi != null)
                {
                    //get facebook user object
                    facebook.Schema.user fbUser = fbApi.users.getInfo();
                    //get user's name
                    fbUserName = fbUser.first_name + " " + fbUser.last_name;
                }

                //add new fb user info to database
                FacebookUser FacebookUser = new FacebookUser();
                //set properties
                FacebookUser.UserId = fbUserId;
                FacebookUser.UserName = fbUserName;
                FacebookUser.PermissionStatus = "";
                IsNewFacebookUser = true;
                //add to database
                dc.FacebookUsers.InsertOnSubmit(FacebookUser);
                dc.SubmitChanges();
            }
        }

        //loads facebook api session
        public API LoadFBApi()
        {
            API fbApi = new API();
            //set its properties
            fbApi.ApplicationKey = ConfigurationManager.AppSettings["FBApiKey"];
            fbApi.Secret = ConfigurationManager.AppSettings["FBSecretKey"];
            fbApi.SessionKey = FBSession.SessionKey;
            fbApi.uid = Int64.Parse(FBSession.UserID);
            return fbApi;
        }
    }
}
